package com.bootdo.lgs.ordertrace.service.impl;

import com.bootdo.common.utils.K100HttpRequest;
import com.bootdo.common.utils.MD5;
import com.bootdo.lgs.order.model.LgsOrder;
import com.bootdo.lgs.ordertrace.dao.OrderTraceMapper;
import com.bootdo.lgs.ordertrace.model.*;
import com.bootdo.lgs.ordertrace.service.OrderTraceService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class OrderTraceServiceImpl implements OrderTraceService {

	private static final Logger logger = LoggerFactory.getLogger(OrderTraceServiceImpl.class);

	@Value("${python.wechatPath}")
	private String ServicePath;

	@Value("${uploadFilePath}")
	private String uploadFilePath;

	@Autowired
	OrderTraceMapper orderTraceMapper;

	@Override
	public OrderTrace getById(Long id) {
		return orderTraceMapper.findById(id);
	}

	@Override
	public boolean modify(Map condition) {
		return orderTraceMapper.updateByCondition(condition) > 0;
	}

	@Override
	public boolean delete(Long id) {
		return orderTraceMapper.deleteById(id) > 0;
	}

	@Override
	public List<LgsOrder> getUnCheckOrderTrace(UnCheckCondition condition) {
		try {
			return orderTraceMapper.getUnCheckOrderTrace(condition);
		} catch (Exception e) {
			logger.warn("查询未签收订单失败",e);
			return new ArrayList<>();
		}
	}

	@Override
	public List getListFromRemote(String com,String num,Long orderId) {

		//String param ="{\"com\":\"annengwuliu\",\"num\":\"300269633145\"}";
		String param ="{\"com\":\"" +
				com +
				"\",\"num\":\"" +
				num +
				"\"}";
//		String customer ="05485DC4678EE23413CEB1068883E511";
//		String key = "LEARYYMZ8073";

		String customer ="E51469EED93617D5104D510DC1161933";
		String key = "jAZVlcQM306";

		String sign = MD5.encode(param+key+customer);
		HashMap params = new HashMap();
		params.put("param",param);
		params.put("sign",sign);
		params.put("customer",customer);
		String resp;
		try {
			resp = new K100HttpRequest().postData("http://poll.kuaidi100.com/poll/query.do", params, "utf-8").toString();
			//String url = "http://poll.kuaidi100.com/poll/query.do";
			//String param = "cdkey=" + sn + "&password=" + key;
			//url = url + "?" + param;
//                String responseString = HttpClientUtil.getInstance().doPostRequest(url);
//                responseString = responseString.trim();
			System.out.println(resp);
			List<Map> orderList = new ArrayList<>();
			// 格式化数据
			JSONObject reslut = JSONObject.fromObject(resp);
			Object checkObj = reslut.get("ischeck");//是否签收标记，1 已签收 0 未签收
			Object stateObj = reslut.get("state");//快递单当前签收状态，包括0在途中、1已揽收、2疑难、3已签收、4退签、5同城派送中、6退回、7转单等7个状态
			JSONArray kuaidiList = (JSONArray) reslut.get("data");
			if (kuaidiList != null && kuaidiList.size() > 0) {
				for (int i = 0; i < kuaidiList.size(); i++) {
					JSONObject jobj = JSONObject.fromObject(kuaidiList.get(i));
					Map<Object, Object> map = new HashMap<Object, Object>();
					map.put("ftime", jobj.get("ftime"));
					map.put("context", jobj.get("context"));
					map.put("orderId", orderId);
					map.put("ischeck", checkObj);
					orderList.add(map);
				}
			}

			System.out.println(orderList);
			//System.out.println("是否签收："+orderList.get(0).get("ischeck"));
			return orderList;
		} catch (Exception e) {
			//e.printStackTrace();
			logger.warn("定时任务查询快递100接口失败，订单id："+orderId+",物流编码："+com+",物流单号："+num,e);
		}

		return null;
	}

	@Override
	public List getListFromDb(OrderTraceQuery condition) {
		//System.out.println("======ServicePath:" +ServicePath+"======");
		//System.out.println("======uploadFilePath:" +uploadFilePath+"======");
		List<OrderTrace> list = orderTraceMapper.getList(condition.getOrderId());
		List<OrderTrace> newList = new ArrayList<>();
		if (list != null && list.size() > 0)
			newList = list.stream().sorted(Comparator.comparing(OrderTrace::getFtime).reversed()).collect(Collectors.toList());
		return newList;
	}

	@Override
	public boolean refreshOrderTrace(OrderTraceCondition condition) {
		List<Map> orderList = getListFromRemote(condition.getCom(),condition.getNum(),condition.getOrderId());
		if(orderList==null||orderList.isEmpty())
			return true;
        deleteOrderTrace(condition.getOrderId());//删除订单跟踪信息
		saveOrderTrace(orderList);//保存订单跟踪信息
		return true;
	}

	@Override
	public boolean deleteOrderTrace(Long orderId) {
		orderTraceMapper.deleteByOrderId(orderId);
		return true;
	}

	@Transactional
	@Override
	public boolean batchRefreshOrderTrace(List<LgsOrderStatusUpdate> lgsOrderStatusUpdateList,List<Long> orderIds,List<Map> condition) {
		//批量更新物流状态
		if(lgsOrderStatusUpdateList!=null&&!lgsOrderStatusUpdateList.isEmpty())
			batchUpdateByCnt(lgsOrderStatusUpdateList,200);
		//批量删除订单跟踪信息
        if(orderIds!=null&&!orderIds.isEmpty())
			batchDelete(orderIds);
        //批量保存订单跟踪信息
        if(condition!=null&&!condition.isEmpty())
			batchSaveByCnt(condition,200);
		return true;
	}

	/** 批量更新状态，每次更新 cnt 条 */
	private void batchUpdateByCnt(List<LgsOrderStatusUpdate> condition, int cnt) {
		if (condition.size() <= cnt)
			batchUpdate(condition);
		else {
			List<LgsOrderStatusUpdate> list = new ArrayList<>();
			for (LgsOrderStatusUpdate sr : condition) {
				list.add(sr);
				if (list.size() == cnt) {
					batchUpdate(list);
					list.clear();
				}
			}
			if (list.size() > 0)
				batchUpdate(list);
		}
	}

	@Override
	public boolean batchUpdate(List<LgsOrderStatusUpdate> condition) {
		try {
			orderTraceMapper.batchUpdate(condition);
		} catch (Exception e) {
			logger.warn("批量更新物流状态失败："+condition,e);
			return false;
		}
		return true;
	}

	@Override
	public boolean batchDelete(List<Long> orderIds) {
		try {
			orderTraceMapper.batchDelete(orderIds);
		} catch (Exception e) {
			logger.warn("批量删除跟踪信息失败："+orderIds.toString(),e);
			return false;
		}
		return true;
	}

	/** 批量更新状态，每次更新 cnt 条 */
	private void batchSaveByCnt(List<Map> condition, int cnt) {
		if (condition.size() <= cnt)
			saveOrderTrace(condition);
		else {
			List<Map> list = new ArrayList<>();
			for (Map sr : condition) {
				list.add(sr);
				if (list.size() == cnt) {
					saveOrderTrace(list);
					list.clear();
				}
			}
			if (list.size() > 0)
				saveOrderTrace(list);
		}
	}

	@Override
	public boolean saveOrderTrace(List<Map> condition) {
		try {
			orderTraceMapper.batchAdd(condition);
		} catch (Exception e) {
			logger.warn("批量保存跟踪信息失败："+condition.toString(),e);
			return false;
		}
		return true;
	}


}
